package com.studyroom.controller;

import com.studyroom.common.Result;
import com.studyroom.entity.User;
import com.studyroom.exception.ServiceException;
import com.studyroom.service.UserService;
import com.studyroom.service.VerificationCodeService;
import com.studyroom.utils.JwtTokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/users")
public class UserController {
    
    private static final Logger log = LoggerFactory.getLogger(UserController.class);
    
    @Autowired
    private VerificationCodeService verificationCodeService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    
    @PostMapping("/verify-code")
    public Result sendVerificationCode(@RequestBody Map<String, String> params) {
        try {
            String username = params.get("username");
            String email = params.get("email");
            
            if (username == null || email == null) {
                return Result.error("用户名和邮箱不能为空");
            }
            
            verificationCodeService.sendVerificationCode(username, email);
            return Result.success();
        } catch (ServiceException e) {
            // 这是我们的业务逻辑异常，直接返回具体错误信息
            log.warn("验证码发送业务异常: {}", e.getMessage());
            return Result.error(e.getMessage());
        } catch (Exception e) {
            // 其他未预期的异常
            log.error("验证码发送系统异常", e);
            return Result.error("系统错误，请稍后重试");
        }
    }
    
    @PostMapping("/reset-password")
    public Result resetPassword(@RequestBody Map<String, String> params) {
        String username = params.get("username");
        String email = params.get("email");
        String verificationCode = params.get("verificationCode");
        String newPassword = params.get("newPassword");
        
        if (username == null || email == null || verificationCode == null || newPassword == null) {
            return Result.error("参数不完整");
        }
        
        Map<String, Object> resetResult = userService.resetPassword(username, email, verificationCode, newPassword);
        
        if ((Boolean) resetResult.get("success")) {
            return Result.success();
        } else {
            return Result.error((String) resetResult.get("message"));
        }
    }
    
    @PostMapping("/profile")
    public Result<User> updateProfile(@RequestBody User user, @RequestHeader("Authorization") String token) {
        if (token != null && token.startsWith("Bearer ")) {
            String jwt = token.substring(7);
            String username = jwtTokenUtil.extractUsername(jwt);
            User currentUser = userService.getUserByUsername(username);
            if (currentUser != null) {
                // 只允许更新特定字段
                currentUser.setPhone(user.getPhone());
                currentUser.setEmail(user.getEmail());
                currentUser.setAvatarUrl(user.getAvatarUrl());
                
                userService.updateById(currentUser);
                
                // 清除敏感信息
                currentUser.setPassword(null);
                return Result.success(currentUser);
            }
        }
        return Result.error("更新用户信息失败");
    }

    /**
     * 获取当前用户信息
     */
    @GetMapping("/info")
    public Result<User> getUserInfo(@RequestHeader("Authorization") String token) {
        log.info("获取用户信息, token: {}", token);
        
        if (token != null && token.startsWith("Bearer ")) {
            String jwt = token.substring(7);
            String username = jwtTokenUtil.extractUsername(jwt);
            
            log.info("从token中提取的用户名: {}", username);
            
            User user = userService.getUserByUsername(username);
            if (user != null) {
                // 清除敏感信息
                user.setPassword(null);
                return Result.success(user);
            }
        }
        
        return Result.error("获取用户信息失败");
    }
} 